import {FC,useEffect} from "react"
import {useRoutes,useNavigate,useLocation} from "react-router-dom"
import useStorage from "./useStorage"

//定义类型
interface Iprops {
    routes: RouteObj[];  // routes配置
    tokenKey: string   //token的key
}

const useRouteWithGuard: FC<Iprops> = (props) => {

    //数据的解构
    let { routes,tokenKey} = props;

    //根据传入的tokenkey从本地获取token
    
    //需求 关闭页面退出登录 将token存到sessionStorage
    //默认将token存到localstorage

    let [token, methods] = useStorage("qf-token")
    // let [token, methods] = useStorage("qf-token","sessionStorage")
    // methods.set("565656")
    // let token = methods.get()

    console.log(token);
    // methods.set("999") 
    // methods.rm()

    // let [s,m] = useStorage("gg")
    // m.set(520)

    //获取当前访问的路径
    let location = useLocation();
    console.log(location);

    // 编程式导航
    let navigate = useNavigate()
    
    //判断有没有token
    useEffect(() => {
        if(!token){
            //访问的页面是不是登入页
            if(location.pathname !== "/login"){
                //跳转到登录页
                navigate("/login")
            }
        }
    },[location])
    

    let element = useRoutes(routes)

    return element
}

export default useRouteWithGuard